package com.sali.handler;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: sali
 * @date: 2025/2/21 下午11:09.
 * @version: 1.0
 */
@Component
@Slf4j
public class FileHandler {



    /**
    * description: 根据文件路径解析数据
    **/
    public String handle(Resource resourceFile) {
        try {
            log.info("正在准备解析{}文件", resourceFile.getURL());

            File file = resourceFile.getFile();
            if (file.isFile()) {
                return fileHandle(file);
            } else if (file.isDirectory()) {
                File[] files = file.listFiles();
                List<File> fileList = Arrays.stream(files).filter(File::isFile).collect(Collectors.toList());
                int index = RandomUtil.randomInt(0, fileList.size());
                File tempfile = fileList.get(index);
                if (tempfile != null) {
                    return fileHandle(tempfile);
                }
            } else {
                log.error("待解析文件路径非文件路径,请检查配置是否为文件绝对路径");
            }
        } catch (Exception e) {
            log.error("文件读取异常.", e);
        }
        return null;
    }

    /**
    * description: 解析文件
    **/
    public String fileHandle(File file) {
        List<String> messages = FileUtil.readLines(file, StandardCharsets.UTF_8);
        if (messages != null && !messages.isEmpty()) {
            int i = RandomUtil.randomInt(messages.size());
            return messages.get(i);
        } else {
            return null;
        }
    }
}
